<template>
    <div class="layout">
        <div class="main-box">
            <div class="searcher-box">
                <Searcher :searcherType="searcherType" :query="pageData.query" @getList="getList" />
            </div>
            <div class="table-box" v-loading="purchaseLoading">
                <el-table
                    ref="singleTableRef"
                    :data="tableData"
                    :cell-style="{background: 'var(--el-table-tr-bg-color)'}"
                    style="width: 100%" border>
                    <el-table-column width="55" fixed>
                        <template #default="{ row }">
                            <el-radio
                                class="radio"
                                :label="row"
                                v-model="currentRow">
                                &emsp;&emsp;&emsp;
                            </el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" width="55" fixed/>
                    <el-table-column prop="product_name" label="&nbsp&nbsp&nbsp商品名称" width="180" fixed>
                        <template #default="{ row }">
                            <el-button type="primary" text @click="handleComponent('view', row)">
                                <span>{{ row.product_name }}</span>
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="供应商" prop="supplierName" width="180" />
                    <el-table-column prop="brand_or_style" label="牌号/款式"  width="180" />
                    <el-table-column prop="internal_brand" label="内部牌号"  width="180" />
                    <el-table-column prop="specification" label="规格"  width="180" />
                    <el-table-column label="采购数量/重量" width="180">
                        <template #default="{ row }">
                            {{ row.productQuantity ? row.productQuantity + row.quantityUnit : "未记录" }} / {{ row.productWeight ? row.productWeight + row.weightUnit : "未记录" }}
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" width="120">
                        <template #default="{ row }">
                            {{ row.unit_price + row.priceUnit}} 
                        </template>
                    </el-table-column>
                    <el-table-column prop="productSum" label="总金额" width="180" />
                    <el-table-column prop="purchaseTime" label="该批次采购时间" width="180" />
                    <el-table-column prop="description" label="商品描述" width="280" />
                    <el-table-column label="状态" width="100" fixed="right">
                        <template #default="{ row }">
                            <el-tag v-if="row.adjustmentStatus !=3" :type="handleState(row.adjustmentStatus)">
                                {{ translateType(row.adjustmentStatus) }}
                            </el-tag>
                            <el-tooltip
                                effect="dark"
                                :content="row.adjustmentDescription"
                                placement="top"
                            >
                                <el-tag v-if="row.adjustmentStatus == 3 && row.adjustmentStatus" type="danger">
                                    {{ translateType(row.adjustmentStatus) }}
                                </el-tag>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="供应商评分" width="180" fixed="right">
                        <template #default="{ row }">
                            <el-rate
                                v-model="row.singleScore"
                                allow-half
                                disabled
                                text-color="#ff9900"
                                :max="5"
                                v-if="row.singleScore&&!(row.singleScore<0)"
                            />
                            <el-popover :visible="popoverVisible[row.id]" trigger="manual" placement="top" :width="300" v-if="!(row.singleScore&&row.score)||(row.singleScore<0&&row.score<0)">
                                <p>单次采购供应商行为评价：</p>
                                <el-form label-width="auto" :model="formData">
                                    <el-form-item label="产品不合格数：" style="width: 98%">
                                        <el-input-number v-model="formData.nonConformities" controls-position="right">
                                            <template #suffix>
                                                <span>pcs/kg</span>
                                            </template>
                                        </el-input-number>
                                    </el-form-item>
                                    <el-form-item label="产品退货数：" style="width: 98%">
                                        <el-input-number v-model="formData.returnGoods" controls-position="right">
                                            <template #suffix>
                                                <span>pcs/kg</span>
                                            </template>
                                        </el-input-number>
                                    </el-form-item>
                                    <el-form-item label="交货延时：" style="width: 98%">
                                        <el-input-number v-model="formData.delay" controls-position="right">
                                            <template #suffix>
                                                <span>天</span>
                                            </template>
                                        </el-input-number>
                                    </el-form-item>
                                    <el-form-item label="本单重要程度：" style="width: 98%">
                                        <el-input-number v-model="formData.α" controls-position="right">
                                            <template #suffix>
                                                <span>%</span>
                                            </template>
                                        </el-input-number>
                                    </el-form-item>
                                    <el-form-item label="服务态度：" style="width: 98%">
                                        <el-rate
                                            v-model="formData.service"
                                            allow-half
                                            text-color="#ff9900"
                                            :max="5"
                                        />
                                    </el-form-item>
                                </el-form>
                                <div style="margin-top: 20px">
                                    <el-button size="small" type="info" @click="popoverVisible[row.id] = false">取消</el-button>
                                    <el-button size="small" type="primary" @click="handleComponent('evaluate', row)">确认</el-button>
                                </div>
                                <template #reference>
                                    <el-button v-if="(!(row.singleScore&&row.score)||(row.singleScore<0&&row.score<0))&&row.used != 1" type="primary" @click="handleComponent('inBound', row)">{{ row?.supplierId ? "入库并评价" : "入库" }}</el-button>
                                    <span v-if="row.used">快捷创建无评分</span>
                                </template>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right">
                        <template #default="{ row }" width="80">
                            <span style="color: #ff9900;" v-if="row.score&&!(row.score<0)">{{ "(" + row.score + ")" }}&nbsp分</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div style="margin: 20px;">
                <el-button type="primary" @click="handleComponent('add')">新增批次采购信息</el-button>
                <el-button type="primary" @click="handleComponent('edit')">编辑批次采购信息</el-button>
                <el-button type="info" @click="handleComponent('del')">删除</el-button>
            </div>
            <Edit :query="formQuery" :dialogVisible="dialogEditVisible" @updateData="updateData" :getList="getList"/>
            <Details :query="formQuery" :dialogVisible="dialogViewVisible" @viewData="viewData" :getList="getList"/>
            <div class="pagination-box">
                <Pagination :background="true" :currentPage="pageData.query.pageNo" :pageSize="pageData.query.pageSize" :total="total" @getList="getList" />
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, onMounted, reactive, toRefs } from 'vue'
import { purchaseDelete , purchasePage , purchaseEvaluate, inBound, productInBound, getSpecificationForm, ifInBound, updateAdjustmentStatus } from "./service/api"
import Searcher from './components/searcher.vue'
import Pagination from './components/pagination.vue'
import Edit from './components/edit.vue'
import Details from './components/details.vue'
import pageData from './service/pageService'
import { ElMessage } from 'element-plus'
import axios from 'axios'
export default defineComponent({
    components: {
        Searcher,
        Pagination,
        Edit,
        Details
    },
    setup() {
      const state = reactive({
        purchaseLoading: false,
        searcherType: 0,
        tableData:[
            // {
            //     id:1,
            //     product_name:"铁",
            //     supplierName: "XXX有限公司",
            //     brand_or_style: null,
            //     internal_brand: null,
            //     productWeight:30,
            //     weightUnit:"kg",
            //     unit_price: 2,
            //     priceUnit: "元/kg",
            //     specification: null,
            //     is_quantity_based: 0,
            //     productSum:14511.24,
            //     purchaseTime: '2016-05-02',
            //     adjustmentStatus:0,
            //     adjustmentDescription:"原材料实际数量对不上",
            //     description:"很贵啊啊啊啊啊啊啊啊啊啊啊啊啊",
            //     // singleScore: 4,
            //     // score:80,
            // },
        ],
        formData:{
            nonConformities: 0,
            returnGoods: 0,
            service: 0,
            delay: 0,
        },
        scoreData:{
            α:0.3,
            singleScore: 0,
            score:0,
        },
        currentRow:null,
        dialogEditVisible:false,
        dialogViewVisible:false,
        formQuery:null,
        total:null,
        popoverVisible:[],
      })
      const calculate = (val) => {
        console.log("val",val)
        converseUnit(val)
        let qualityCapability = null
        let deliveryCapacity = null
        let serviceCapacity = null
        console.log("state.formData.service",state.formData.service)
        if(pageData.unitConversion.piece && val.is_quantity_based == 1)
        {
            qualityCapability = 100*(1-state.formData.nonConformities/pageData.unitConversion.piece)
            deliveryCapacity = 50*(1-state.formData.returnGoods/pageData.unitConversion.piece) + 50-10*state.formData.delay
            serviceCapacity = state.formData.service*20
        }else if(pageData.unitConversion.amount && val.is_quantity_based == 0)
        {
            qualityCapability = 100*(1-state.formData.nonConformities/pageData.unitConversion.amount)
            deliveryCapacity = 50*(1-state.formData.returnGoods/pageData.unitConversion.amount) + 50-10*state.formData.delay
            serviceCapacity = state.formData.service*20
        }
        state.scoreData.score = qualityCapability*0.4 + deliveryCapacity*0.3 + serviceCapacity*0.3
        state.scoreData.singleScore = state.scoreData.score/20
        console.log("qualityCapability",qualityCapability)
        console.log("deliveryCapacity",deliveryCapacity)
        console.log("serviceCapacity",serviceCapacity)
        console.log("state.scoreData",state.scoreData)
      }
      const getList = (val) => {
        console.log("父组件",val)
        if(val?.pagesize) {
            pageData.query.pageSize = val.pagesize
        }
        if(val?.currentpage) {
            pageData.query.pageNo = val.currentpage
        }
        purchasePage(pageData.query).then((response)=>{
            state.tableData = response.data.data.tableData
            state.total = response.data.data.total
            console.log("Response:", response.data.data.tableData)
            state.purchaseLoading = false
        })
      }
      const handleState = (val) => {
          if (val == 0) return "info"
          else if (val == 1) return "warning"
          else if (val == 2) return "success"
          else if (val == 3) return "danger"
      }
      //判断产品状态类型
      const translateType = (val) => {
          if(val === 0) return "未入库"
          else if(val === 1) return "审核中"
          else if(val === 2) return "已入库"
          else if(val === 3) return "不通过"
      }
      const converseUnit = (row) =>{
          console.log("converseUnit",row)
          pageData.unitConversion.unitPrice = null
          pageData.unitConversion.amount = null
          pageData.unitConversion.piece = null
        if(row?.is_quantity_based == 0 && row?.priceUnit == "元/g"){
            pageData.unitConversion.unitPrice = row?.unit_price*1000
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/kg"){
            pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 0 && row?.priceUnit == "元/T"){
            pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.is_quantity_based == 1 && row?.priceUnit == "元/pcs"){
            pageData.unitConversion.unitPrice = row?.unit_price
        }else if(row?.is_quantity_based == 1 && row?.priceUnit == "元/kpcs"){
            pageData.unitConversion.unitPrice = row?.unit_price/1000
        }
        if(row?.productWeight && row?.weightUnit == "g"){
            pageData.unitConversion.amount = row?.productWeight/1000
        }else if(row?.productWeight && row?.weightUnit == "kg"){
            pageData.unitConversion.amount = row?.productWeight
        }else if(row?.productWeight && row?.weightUnit == "T"){
            pageData.unitConversion.amount = row?.productWeight*1000
        }
        if(row?.productQuantity && row?.quantityUnit == "pcs"){
            pageData.unitConversion.piece = row?.productQuantity
        }else if(row?.productQuantity && row?.quantityUnit == "kpcs"){
            pageData.unitConversion.piece = row?.productQuantity*1000
        }
        console.log("pageData.unitConversion.unitPrice",pageData.unitConversion.unitPrice)
        console.log("pageData.unitConversion.amount",pageData.unitConversion.amount)
        console.log("pageData.unitConversion.piece",pageData.unitConversion.piece)
      }
      // 封装判断isQuantityBased值的函数
      const getIsQuantityBased = (row) => {
        if( row?.type == 3 ) return 1;
        else if( row?.type == 2 ) return 0;
        else if( row?.type == 1 ) return 2;
      }
      const handleComponent = (val,row=state.currentRow) => {
        if(val == "edit")
        {
            console.log('row',row)
            if(!state.currentRow){
                ElMessage({
                    message: '请选择需要被编辑的数据行',
                    type: 'warning',
                })
            }
            else if(row.adjustmentStatus == 0 || row.adjustmentStatus == 3){
                const data = {
                    type:val,
                    title:"编辑",
                    id:row.id,
                    supplierId:row?.supplierId,
                    businessId:row?.businessId,
                }
                state.formQuery = data
                state.dialogEditVisible = true
            }else {
                ElMessage({
                    message: '入库审核中或审核过的产品的信息不可更改',
                    type: 'warning',
                })
            }
            console.log("state.currentRow",state.currentRow)
        }else if(val == "view")
        {
            const data = {
                type:val,
                title:"详情",
                id:row.id,
                supplierId:row?.supplierId,
                businessId:row?.businessId,
            }
            state.formQuery = data
            state.dialogViewVisible = true
        }else if(val == "add")
        {
            const data = {
                type:val,
                title:"新增采购信息",
                supplierId: row?.supplierId,
                businessId: row?.businessId,
            }
            state.formQuery = data
            state.dialogEditVisible = true
        }else if(val == "del")
        {
            if(!state.currentRow){
                ElMessage({
                    message: '请选择需要被删除的数据行',
                    type: 'warning',
                })
            }
            else if (row.adjustmentStatus == 0 || row.adjustmentStatus == 3 || row.adjustmentStatus == 2){
                const data = {
                    id:row.id
                }
                purchaseDelete(data).then((res)=>{
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                    getList()
                })
            }else {
                ElMessage({
                    message: '入库审核中的产品的信息不可删除',
                    type: 'warning',
                })
            }
        }else if(val == "evaluate")
        {
            if(row?.supplierId){
                calculate(row)
                purchaseEvaluate(row?.supplierId,row?.id,state.scoreData).then((res)=>{
                    getList()
                })
            }
            converseUnit(row)
            let isQuantityBased = getIsQuantityBased(row)
            const inBoundData = {
                skuName: row?.product_name,
                skuBrand: row?.brand_or_style?? "",
                internalBrand: row?.internal_brand?? "",
                specification: row?.specification?? "",
                unitPrice: pageData.unitConversion.unitPrice,
                byQuantity: isQuantityBased,
            }
            inBound(inBoundData).then((res)=>{
                console.log("inBound",res)
                let isQuantityBased = getIsQuantityBased(row)
                const data = {
                    productId: res.data.data.id,
                    productName: row?.product_name,
                    brandOrStyle: row?.brand_or_style?? "",
                    internalBrand: row?.internal_brand?? "",
                    specification: row?.specification?? "",
                    isQuantityBased: isQuantityBased,
                    operationType: 3,
                    amount: pageData.unitConversion.amount,
                    piece: pageData.unitConversion.piece,
                    department: "Purchase",
                    noteId: row?.id,
                    description: row?.description,
                }
                productInBound(data).then((res)=>{
                    console.log("入库2",res)
                    if(res.data.success){
                        ElMessage({
                            message: '成功发起入库申请',
                            type: 'success',
                        })
                    }
                    const statusData = {
                        adjustmentStatus:1,
                        adjustmentDescription:null,
                    }
                    updateAdjustmentStatus(row.id,statusData).then((res)=>{
                        console.log("updateAdjustmentStatus",res)
                        getList()
                    })
                })
            })
            state.popoverVisible[row.id] = false
        }else if(val == "inBound"&&((row?.is_quantity_based == 1&&row?.productQuantity)||(row?.is_quantity_based == 0&&row?.productWeight))){
            if(row?.supplierId) state.popoverVisible[row.id] = true
            else {
                state.popoverVisible[row.id] = false
                converseUnit(row)
                let isQuantityBased = getIsQuantityBased(row)
                const inBoundData = {
                    skuName: row?.product_name,
                    skuBrand: row?.brand_or_style?? "",
                    internalBrand: row?.internal_brand?? "",
                    specification: row?.specification?? "",
                    unitPrice: pageData.unitConversion.unitPrice,
                    byQuantity: isQuantityBased,
                }
                inBound(inBoundData).then((res)=>{
                    console.log("inBound",res)
                    let isQuantityBased = getIsQuantityBased(row)
                    const data = {
                        productId: res.data.data.id,
                        productName: row?.product_name,
                        brandOrStyle: row?.brand_or_style?? "",
                        internalBrand: row?.internal_brand?? "",
                        specification: row?.specification?? "",
                        isQuantityBased: isQuantityBased,
                        operationType: 3,
                        amount: pageData.unitConversion.amount,
                        piece: pageData.unitConversion.piece,
                        department: "Purchase",
                        noteId: row?.id,
                        description: row?.description,
                    }
                    productInBound(data).then((res)=>{
                        console.log("入库2",res)
                        if(res.data.success){
                            ElMessage({
                                message: '成功发起入库申请',
                                type: 'success',
                            })
                            const statusData = {
                                adjustmentStatus:1,
                                adjustmentDescription:null,
                            }
                            updateAdjustmentStatus(row.id,statusData).then((res)=>{
                                console.log("updateAdjustmentStatus",res)
                                ifInBound(row?.id).then((res)=>{
                                    getList()
                                })
                            })

                            localStorage.setItem(`ifInBound_${row.id}`, "true")
                        }
                    })
                })
            }
        }
        else {
            ElMessage({
                message: '计价与计量方式不统一，请编辑信息以完善价格核算',
                type: 'warning',
            })
        }
      }
      const updateData = (val) =>{
        state.dialogEditVisible = val
        console.log("state.dialogVisible ",state.dialogEditVisible )
      }
      const viewData = (val) =>{
        state.dialogViewVisible = val
        console.log("state.dialogVisible ",state.dialogViewVisible )
      }
      onBeforeMount((row) => {
        state.purchaseLoading = true
        getList()
        getSpecificationForm().then((res)=>{
            console.log("规格表",res)
        })
        //用于测试审核状态
        // const statusData = {
        //     adjustmentStatus:3,
        //     adjustmentDescription:"对不上",
        // }
        // updateAdjustmentStatus(50,statusData).then((res)=>{
        //     console.log("updateAdjustmentStatus",res)
        //     getList()
        // })
        //localStorage.clear()
        // 初始化 ifInBound 状态（从 localStorage 读取）
        // state.tableData.forEach(row => {
        //     pageData.ifInBound[row.id] = localStorage.getItem(`ifInBound_${row.id}`) === "true";
        // })
      })
      return {
        ...toRefs(state),
        getList,
        handleComponent,
        pageData,
        updateData,
        viewData,
        handleState,
        translateType
      }
    }
})
</script>

<style  scoped>
.layout{
    width: 100%;
    height: 100%;
    background-color: #F5F6F9;
    padding-top: 20px;
}
.main-box{
    width: 98%;
    height: 100%;
    background-color: #FFFFFF;
    margin: auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}
.searcher-box{
    margin-top: 20px;
    height: 100px;
    width: 96%;
    margin-left: auto;
    margin-right: auto;
}
.table-box{
    height: 80%;
    width: 96%;
    margin-top: 40px;
    margin-left: auto;
    margin-right: auto;
    overflow: auto; /* 添加滚动条 */
}
.pagination-box{
    height: 100px;
    width: 100%;
    background-color: #FFFFFF;
    margin-left: auto;
    margin-right: auto;
}

.el-table {
    --el-table-header-bg-color: var(--el-bg-color-page);
    --el-table-border-color: var(--el-border-color-dark);
    --el-table-header-text-color: var(--el-text-color-primary);
}
:deep(.el-table .hovering-row) {
  --el-table-tr-bg-color: #f5f7fa;
}

</style>